//
//  StopWatchViewController.m
//  AlarmClock
//
//  Created by aaaa on 2016/9/29.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "BSKStopWatchViewController.h"
#import "BSKTimePicker.h"
#import "SDAutoLayout.h"
#import "BSKConsts.h"
#import "BSKSington.h"
#import "BSKCancelAlarmClockViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface BSKStopWatchViewController ()<BSKTimPickerDelegate>
@property (nonatomic,strong) BSKTimePicker * timePicker;
@property (nonatomic,strong) UIButton * startButton;
@property (nonatomic,strong) UIButton * stopButton;
//@property (nonatomic,strong) UIButton * ringButton;
@property (nonatomic,strong) UILabel * startLabel;
@property (nonatomic,strong) UILabel * stopLabel;
//@property (nonatomic,strong) UILabel * ringLabel;
@property (nonatomic,strong) dispatch_source_t timerSource;
@property (nonatomic,assign) BOOL creatNewLocalNotify;
@property (nonatomic,strong) AVAudioPlayer * player;
@end

@implementation BSKStopWatchViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"timer_tick" ofType:@"wav"];
    NSURL * fileURL = [NSURL fileURLWithPath:filePath];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL fileTypeHint:@"wav" error:NULL];
    self.player.numberOfLoops = -1;
    [self.player prepareToPlay];
    _creatNewLocalNotify = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:@"applicationDidEnterBackground" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:@"applicationWillEnterForeground" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didResaveStopWatchAlertNotification:) name:@"StopWatchAlertNotification" object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [self checkNotifys];
}
-(void)checkNotifys{
    for(UILocalNotification * notification in [UIApplication sharedApplication].scheduledLocalNotifications){
        if ([[notification.userInfo objectForKey:@"id"] isEqualToString:@"StopWatchNoti"]) {
            NSInteger notifySecondes = (NSInteger)notification.fireDate.timeIntervalSinceNow;
            NSLog(@"有一个倒计时:%ld",notifySecondes);
            NSInteger h = (NSInteger)notifySecondes/3600;
            NSInteger m = (NSInteger)(notifySecondes - h*3600)/60;
            NSInteger s = (NSInteger)(notifySecondes - h*3600 - m*60);
            NSLog(@"====%ld:%ld:%ld",h,m,s);
            self.timePicker.hours = h;
            self.timePicker.minutes =m;
            self.timePicker.seconds = s;
            _creatNewLocalNotify = NO;
            self.startButton.selected = NO;
            [self startButtonAction:self.startButton];
            break;
        }
    }
}

-(void)initializeUserInterface{
    self.view.backgroundColor= [UIColor clearColor];
    self.timePicker = [[BSKTimePicker alloc]initWithFrame:CGRectMake(50, 100, 200, 200)];
    self.timePicker.center = self.view.center;
    self.timePicker.minutesPointColor = [UIColor colorWithRed:1.0f green:87.0f/255.0f blue:42.0f/255.0f alpha:1.0f];
    self.timePicker.secondsPointColor = [UIColor colorWithRed:0.0f green:150.0f/255.0f blue:1.0f alpha:1.0f];
    self.timePicker.minutesCircleColor = [UIColor whiteColor];
    self.timePicker.secondsCircleColor = [UIColor whiteColor];
    self.timePicker.textColor = [UIColor whiteColor];
    self.timePicker.delegate = self;
    self.timePicker.minutesPointSize = 20;
    self.timePicker.secondsPointSize = 15;
    [self.view addSubview:self.timePicker];
    
    self.timePicker.sd_layout
    .topSpaceToView(self.view,0)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .heightEqualToWidth();
    
    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_start_normal"] forState:UIControlStateNormal];
    [self.startButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_stop_normal"] forState:UIControlStateSelected];
    [self.startButton addTarget:self action:@selector(startButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.startButton];
    
    self.stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.stopButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_reset_normal"] forState:UIControlStateNormal];
    [self.stopButton addTarget: self action:@selector(stopButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.stopButton];
    
    
//    self.ringButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.ringButton setBackgroundImage:[UIImage imageNamed:@"timer_btn_ring_normal"] forState:UIControlStateNormal];
//    [self.view addSubview:self.ringButton];
    
    self.stopButton.sd_layout
    .centerXIs(self.view.width/2+self.view.width/6-5)
    .widthIs(self.view.width/3-10)
    .heightEqualToWidth()
    .bottomSpaceToView(self.view,40);
    
    self.startButton.sd_layout
    .centerYEqualToView(self.stopButton)
    .rightSpaceToView(self.stopButton,10)
    .widthIs(self.view.width/3-10)
    .heightEqualToWidth();
    
//    self.ringButton.sd_layout
//    .centerYEqualToView(self.stopButton)
//    .leftSpaceToView(self.stopButton,10)
//    .widthIs(self.view.width/3-10)
//    .heightEqualToWidth();
    
    
    self.startLabel = [[UILabel alloc]init];
    self.startLabel.text = @"开始";
    self.startLabel.alpha = 0.2;
    self.startLabel.font = [UIFont systemFontOfSize:15];
    self.startLabel.textAlignment = NSTextAlignmentCenter;
    self.startLabel.textColor = [UIColor whiteColor];
    [self.view addSubview: self.startLabel];
    
    self.startLabel.sd_layout
    .leftEqualToView(self.startButton)
    .rightEqualToView(self.startButton)
    .heightIs(30)
    .topSpaceToView(self.startButton,0);
    
    
    self.stopLabel = [[UILabel alloc]init];
    self.stopLabel.text = @"重置";
    self.stopLabel.alpha = 0.2;
    self.stopLabel.font = [UIFont systemFontOfSize:15];
    self.stopLabel.textAlignment = NSTextAlignmentCenter;
    self.stopLabel.textColor = [UIColor whiteColor];
    [self.view addSubview: self.stopLabel];
    
    self.stopLabel.sd_layout
    .leftEqualToView(self.stopButton)
    .rightEqualToView(self.stopButton)
    .heightIs(30)
    .topSpaceToView(self.stopButton,0);
    
    
//    self.ringLabel = [[UILabel alloc]init];
//    self.ringLabel.text = @"铃声";
//    self.ringLabel.font = [UIFont systemFontOfSize:15];
//    self.ringLabel.textAlignment = NSTextAlignmentCenter;
//    self.ringLabel.textColor = [UIColor whiteColor];
//    [self.view addSubview: self.ringLabel];
//    
//    self.ringLabel.sd_layout
//    .leftEqualToView(self.ringButton)
//    .rightEqualToView(self.ringButton)
//    .heightIs(30)
//    .topSpaceToView(self.ringButton,0);
    
    
    self.startButton.userInteractionEnabled = NO;
    self.stopButton.userInteractionEnabled = NO;
    self.startButton.alpha = 0.2;
    self.stopButton.alpha = 0.2;
    
}


#pragma mark ButtonAction

-(void)startButtonAction:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        if(self.timePicker.hours ==0 && self.timePicker.minutes ==0 && self.timePicker.seconds == 0){
            sender.selected = NO;
            return;
        }
        [self.player play];
        self.stopButton.userInteractionEnabled = NO;
        self.stopButton.alpha = 0.2;
        self.stopLabel.alpha = 0.2;
        self.timePicker.userInteractionEnabled = NO;
        self.startLabel.text = @"暂停";
        /// 初始化一个gcd队列.
        
        dispatch_queue_t timerQueue = dispatch_queue_create("timerQueue", 0);
        
        /// 创建 gcd timer.
        
        _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);
        
        double interval = 1 * NSEC_PER_SEC; /// 间隔
        
        dispatch_source_set_timer(_timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
        /// 定时器block设置
        dispatch_source_set_event_handler(_timerSource, ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timePicker.seconds-=1;
            });
        });
        /// 唤起定时器任务.
        dispatch_resume(_timerSource);
        
        //------
        
        if (!_creatNewLocalNotify) {
            return;
        }
        
        //新建一个本地通知
        UILocalNotification *locNoti = [[UILocalNotification alloc]init];
        
        //1.设置通知的必须项
        //1.1 设置通知的内容
        locNoti.alertBody = @"您设置的时间已经到了！！";
        
        //1.2 设置通知的发送时间
        locNoti.fireDate = [NSDate dateWithTimeIntervalSinceNow:self.timePicker.seconds+self.timePicker.minutes*60+self.timePicker.hours*3600-1];
        //设置重复时间
        locNoti.repeatInterval = NSCalendarUnitMinute;
        NSDate * date = [NSDate date];
        NSDateFormatter * formater = [[NSDateFormatter alloc]init];
        [formater setDateFormat:@"yyyy/MM/dd hh:mm:ss"];
        
        locNoti.userInfo = @{@"id":@"StopWatchNoti",@"date":[formater stringFromDate:date]};
        //1.3 设置时区,一般默认
        locNoti.timeZone = [NSTimeZone defaultTimeZone];
        //1.4 设置弹框的启动图片(无论此处填什么, 都只是读取默认的启动图片)
        // (iOS9.0之后, 就没有效果)
        locNoti.alertLaunchImage = @"timer_btn_ring_normal.png";
        
        //1.5 设置弹框的标题
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.2) {
            locNoti.alertTitle = @"时间到了！！";
        }
        
        // 设置滑动解锁的文字
        locNoti.hasAction = YES; // 如果是NO,则下面配置的字符串提醒, 没有效果
        locNoti.alertAction = @"通知的alertAction";
        
        // 设置通知接收到时的声音(30s)
        locNoti.soundName = @"ring.wav";
        
        // 设置通知发送时, 提醒数字(==0, 会自动消失)
        locNoti.applicationIconBadgeNumber = 0;
        
        // 2. 发送通知
        // 通知是一个应用程序级别的操作, openURL
        // 立即推送一个通知
        //    [[UIApplication sharedApplication]presentLocalNotificationNow:locNoti];
        [[UIApplication sharedApplication]scheduleLocalNotification:locNoti];
    }
    else{
        [self.player stop];
        self.startLabel.text = @"继续";
        self.stopButton.userInteractionEnabled = YES;
        self.stopButton.alpha = 1;
        self.stopLabel.alpha = 1;
        if (_timerSource) {
            dispatch_source_cancel(_timerSource);
        }
        NSArray * notis = [UIApplication sharedApplication].scheduledLocalNotifications;
        for (UILocalNotification * noti in notis) {
            if ([[noti.userInfo objectForKey:@"id"] isEqualToString:@"StopWatchNoti"]) {
                [[UIApplication sharedApplication] cancelLocalNotification:noti];
                break;
            }
        }
    }
}


-(void)stopButtonAction:(UIButton *)sender{
    if (_timerSource) {
        dispatch_source_cancel(_timerSource);
    }
    [self.player stop];
    self.stopButton.selected = YES;
    self.timePicker.seconds = 0;
    self.timePicker.minutes = 0;
    self.timePicker.hours = 0;
    self.stopButton.selected = NO;
    self.startButton.userInteractionEnabled = NO;
    self.startButton.selected = NO;
    self.startButton.alpha = 0.2;
    self.startLabel.text = @"开始";
    self.startLabel.alpha = 0.2;
    self.stopButton.userInteractionEnabled = NO;
    self.stopButton.alpha = 0.2;
    self.timePicker.userInteractionEnabled = YES;
    _creatNewLocalNotify = YES;
    for(UILocalNotification * notification in [UIApplication sharedApplication].scheduledLocalNotifications){
        if ([[notification.userInfo objectForKey:@"id"] isEqualToString:@"StopWatchNoti"]) {
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
            break;
        }
    }
}


-(void)ringButtonAction:(UIButton *)sender{
    
}

#pragma mark 应用程序生命周期通知

-(void)applicationWillEnterForeground
{
    [self checkNotifys];
    self.timePicker.playSound = YES;
}
-(void)applicationDidEnterBackground
{
    if (_timerSource) {
        dispatch_source_cancel(_timerSource);
    }
    self.timePicker.playSound = NO;
}

#pragma mark didResaveStopWatchAlertNotification

-(void)didResaveStopWatchAlertNotification:(NSNotification *)notify{
    UILocalNotification * localNotify = notify.object[@"notify"];
    self.startButton.userInteractionEnabled = NO;
    self.startButton.selected = NO;
    self.startButton.alpha = 0.2;
    self.stopButton.userInteractionEnabled = NO;
    self.stopButton.alpha = 0.2;
    self.stopLabel.alpha = 0.2;
    self.startLabel.alpha = 0.2;
    self.startLabel.text = @"开始";
    self.timePicker.userInteractionEnabled = YES;
    _creatNewLocalNotify = YES;
    
    
    BSKCancelAlarmClockViewController *vc = [[BSKCancelAlarmClockViewController alloc]initWithMode:BSKCancelAlarmClockVCStopWatchMode];
    NSNumber *number = [notify.object objectForKey:@"applicationState"];
    if (number && [number integerValue] == UIApplicationStateActive) {
        NSLog(@"程序处于前台活动状态");
    }
    if (number && [number integerValue] == UIApplicationStateInactive) {
        NSLog(@"程序从后台回到前台活动状态");
    }
    if (number && [number integerValue] == UIApplicationStateBackground) {
        NSLog(@"程序被杀死，重新启动到前台活动状态");
        vc.playSound = YES;
    }
    [self.player stop];
    [[BSKSington sharBSKSington].rootViewController pushViewController:vc animated:YES];
//    [self presentViewController:vc animated:YES completion:nil];
    [[UIApplication sharedApplication] cancelLocalNotification:localNotify];
}

#pragma mark BSKTimPickerDelegate

-(void)BSKTimePicker:(BSKTimePicker *)timepicker isSelectingChanged:(BOOL)isSelecting{
    
}


-(void)BSKTimePiker:(BSKTimePicker *)timePicker DidSelectedTimeWithHours:(NSInteger)hours Minutes:(NSInteger)minutes Seconds:(NSInteger)seconds{
    
}

-(void)BSKTimePiker:(BSKTimePicker *)timePicker timeDidChangedWithHours:(NSInteger)hours Minutes:(NSInteger)minutes Seconds:(NSInteger)seconds{
    NSLog(@"%ld:%ld:%ld,%d",hours,minutes,seconds,_startButton.selected);
    if (hours==0&&seconds==0&minutes==0) {
        if (_timerSource) {
            dispatch_source_cancel(_timerSource);
        }
        self.startButton.userInteractionEnabled = NO;
        self.startButton.selected = NO;
        self.startButton.alpha = 0.2;
        self.stopButton.userInteractionEnabled = NO;
        self.stopButton.alpha = 0.2;
        self.stopLabel.alpha = 0.2;
        self.startLabel.alpha = 0.2;
        self.startLabel.text = @"开始";
        self.timePicker.userInteractionEnabled = YES;
    }
    else{
        self.startButton.userInteractionEnabled = YES;
        self.startButton.alpha = 1;
        self.startLabel.alpha = 1;
        if (!self.startButton.selected) {
            self.stopButton.userInteractionEnabled = YES;
            self.stopButton.alpha = 1;
            self.stopLabel.alpha = 1;
        }
    }
}

@end
